#!/usr/bin/env groovy

def git_auth = "1fa96864-5699-483b-a920-2af11df61119"
def image_auth = "1e0ae5b9-b151-45b9-a94f-bd02d803ff22"
def sonarqube_auth = "2a5e8f48-ffe9-4f44-ab63-08af986875e9"

pipeline {
    agent {
        kubernetes {
            yaml '''
apiVersion: v1
kind: Pod
metadata:
  name: jenkins-slave
  namespace: jenkins
spec:
  tolerations:
  - key: "no-pod"
    operator: "Exists"
    effect: "NoSchedule"
  containers:
  - name: docker
    #image: docker:28.1.1
    image: ccr.ccs.tencentyun.com/huanghuanhui/docker:28.1.1
    imagePullPolicy: IfNotPresent
    readinessProbe:
      exec:
        command: [sh, -c, "ls -S /var/run/docker.sock"]
    command:
    - sleep
    args:
    - 99d
    volumeMounts:
    - name: docker-socket
      mountPath: /var/run
  - name: docker-daemon
    #image: docker:28.1.1-dind
    image: ccr.ccs.tencentyun.com/huanghuanhui/docker:28.1.1-dind
    imagePullPolicy: IfNotPresent
    securityContext:
      privileged: true
    volumeMounts:
    - name: docker-socket
      mountPath: /var/run
  - name: maven
    #image: maven:3.8.1-jdk-8
    image: ccr.ccs.tencentyun.com/huanghuanhui/maven:3.8.1-jdk-8
    imagePullPolicy: IfNotPresent
    command:
    - sleep
    args:
    - 99d
    volumeMounts:
    - name: maven-cache
      mountPath: /root/.m2/repository
  - name: kubectl
    image: ccr.ccs.tencentyun.com/huanghuanhui/kubectl:v1.6.0
    imagePullPolicy: IfNotPresent
    command:
    - sleep
    args:
    - 99d
  - name: sonar-scanner
    image: ccr.ccs.tencentyun.com/huanghuanhui/sonar-scanner-cli:11.4
    imagePullPolicy: IfNotPresent
    command:
    - sleep
    args:
    - 99d
  - name: jnlp
    #image: jenkins/inbound-agent:3327.v868139a_d00e0-6
    image: ccr.ccs.tencentyun.com/huanghuanhui/jenkins-inbound-agent:3327.v868139a_d00e0-6
    imagePullPolicy: IfNotPresent
  volumes:
  - name: docker-socket
    emptyDir: {}
  - name: maven-cache
    persistentVolumeClaim:
      claimName: jenkins-slave-maven-cache
'''
        }
    }

environment {
AppName = "${AppName}"
GitRepo = "${GitRepo}"
GitBranch = "${GitBranch}"
Server = "${Server}"
RepoName = "${RepoName}"
BaseImage = "${BaseImage}"
JAVA_OPTS = "${JAVA_OPTS}"
}

    parameters {
        string(name: 'AppName', defaultValue: 'blue-ruoyi-auth', description: '服务名')
        string(name: 'GitRepo', defaultValue: 'https://gitlab.huanghuanhui.com/root/RuoYi-Cloud.git', description: '代码仓库地址')
        string(name: 'GitBranch', defaultValue: 'blue', description: '代码版本')
        string(name: 'Server', defaultValue: 'ccr.ccs.tencentyun.com', description: '仓库地址')
        string(name: 'RepoName', defaultValue: 'huanghuanhui/dev-blue-ruoyi-auth', description: '仓库名字（仓库自动创建）')
        string(name: 'BaseImage', defaultValue: 'ccr.ccs.tencentyun.com/huanghuanhui/openjdk:8-jre', description: '基础镜像')
        string(name: 'JAVA_OPTS', defaultValue: '-Xms2048M -Xmx2048M -Xmn256M -Dspring.config.location=app.yml -Dserver.tomcat.max-threads=800', description: 'jar 运行时的参数配置')
    }
    
    stages {
        stage('拉取代码') {
            steps {
            git branch: "${GitBranch}", credentialsId: "${git_auth}", url: "${GitRepo}"
            }
        }

        stage('代码扫描') {
            steps {
                container('sonar-scanner') {
                    withCredentials([string(credentialsId: "${sonarqube_auth}", variable: 'SONAR_TOKEN')]) {
                        sh """
                        sonar-scanner \
                          -Dsonar.projectKey=${AppName} \
                          -Dsonar.sources=. \
                          -Dsonar.host.url=http://sonarqube-service.sonarqube:9000 \
                        """
                    }
                }
            }
        }

        stage('代码编译') {
            steps {
              container('maven') {
                sh """
                  mvn -U clean install -Dmaven.test.skip=true
                """
                }
            }
        }

        stage('打包镜像') {
            steps {
              script {env.GIT_COMMIT_MSG = sh (script: 'git rev-parse --short HEAD', returnStdout: true).trim()}
              container('docker') {
sh '''cat > entrypoint.sh << EOF
#! /bash/bin -e
env
java $JAVA_OPTS -jar ./*.jar
EOF

cat > app.yml << EOF
# Tomcat
server:
  port: 9200

# Spring
spring:
  application:
    # 应用名称
    name: ${AppName}
  profiles:
    # 环境配置
    active: dev
  cloud:
    nacos:
      discovery:
        # 服务注册地址
        server-addr: nacos-headless.nacos.svc.cluster.local:8848
        namespace: blue-prod
      config:
        # 配置中心地址
        server-addr: nacos-headless.nacos.svc.cluster.local:8848
        namespace: blue-prod
        # 配置文件格式
        file-extension: yml
        # 共享配置
        shared-configs:
          - application
EOF


cat > Dockerfile << EOF
FROM ${BaseImage}
WORKDIR /usr/local/src/
ADD ./ruoyi-auth/target/ruoyi-auth.jar /usr/local/src/ruoyi-auth.jar
ADD app.yml .
ADD entrypoint.sh .
ENTRYPOINT ["sh","./entrypoint.sh"]
EOF

docker build -t ${Server}/${RepoName}:${GitBranch}-${GIT_COMMIT_MSG}-${BUILD_ID} .
'''
                }
            }
        }

        stage('推送镜像') {
            steps {
              container('docker') {
                withCredentials([usernamePassword(credentialsId: "${image_auth}", passwordVariable: 'password', usernameVariable: 'username')]) {
                sh """
                docker login -u ${username} -p '${password}' ${Server}
                docker push ${Server}/${RepoName}:${GitBranch}-${GIT_COMMIT_MSG}-${BUILD_ID}
                """
                   }
                }
            }
        }
    }
}